<?php
namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\exception\HttpResponseException;
use think\Config;
use fast\Random;

class Member extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    //拉卡拉用户
    protected $order_model = null;
    protected $lal_member_model = null;
    protected $lal_member_info_model = null;
    protected $lal_member_entry_model = null;
    //支付模型
    protected $pay_out_trade_model = null;
    protected $wanlshop_pay_model = null;

    //权益卡模型
    protected $order_item_model = null;
    //充值卡续卡模型
    protected $order_item_recharge_model = null;
    //权益卡订单模型
    protected $order_item_info_model = null;

    public function _initialize() 
    {
        date_default_timezone_set('PRC');           // 设置时区

        $this->order_model = new \app\admin\model\wanlshop\Order;
        $this->lal_member_model = new \app\admin\model\lal\Member;
        $this->lal_member_info_model = new \app\admin\model\lal\MemberInfo;
        $this->lal_member_entry_model = new \app\admin\model\lal\MemberEntry;
        $this->pay_out_trade_model = new \app\api\model\wanlshop\PayOutTrade;
        $this->wanlshop_pay_model = new \app\admin\model\wanlshop\Pay;
        $this->order_item_model = new \app\admin\model\order\Item;
        $this->order_item_recharge_model = new \app\admin\model\order\ItemRecharge;
        $this->order_item_info_model = new \app\admin\model\order\ItemInfo;
    }

    /**
     * 会员开户结果通知
     *  member_no       会员编号
     *  out_member_no   外部会员号
     *  mobile          手机号
     *  member_state    会员状态,1=有效，10=锁定，20=关闭，99=待审核    
     *  member_type     会员类型,3=企业会员，2=个人会员，4=个人工商户
     *  card_no         银行卡编号
     * 
     * */
    public function syncmember()
    {
        $params = $this->request->param();
        write_log_record("[".date("Y-m-d H:i:s")."]会员开户结果通知,参数：".json_encode($params));

        $event_type = $this->request->param('event_type','');
       
        $event = $this->request->param('event','');

        if (!$event_type || $event_type != 'member.open' || !$event || empty($event)) {
            $this->error('参数错误');
        }
        // write_log_record("[".date("Y-m-d H:i:s")."]会员开户结果通知,参数：".$event);
        
        $event = json_decode($event,true);

        $card_no = isset($event['card_no'])?$event['card_no']:'';

        $out_member_no = isset($event['out_member_no'])?$event['out_member_no']:'';

        if (!$card_no || empty($card_no) || !$out_member_no || empty($out_member_no)) {
            $this->error('缺少参数！');
        }

        $lal_member_info = $this->lal_member_info_model->where(['out_member_no'=>$out_member_no])->find();

        if (!$lal_member_info || empty($lal_member_info)) {
            $this->error('会员开户同步失败！');
        }

        $lal_member = $this->lal_member_model->where(['lal_id'=>$lal_member_info['id'],'status'=>'1'])->find();
        if ($lal_member && !empty($lal_member)) {
            $this->error('会员开户已同步成功，无需再次同步！');
        }

        Db::startTrans();
        try{
            $up_data = [];
            $up_data['member_no'] = $event['member_no'];
            $up_data['mobile'] = $event['mobile'];
            $up_data['member_state'] = $event['member_state'];
            $up_data['member_type'] = $event['member_type'];
            $up_data['card_no'] = $card_no;

            $up_res = $this->lal_member_info_model->where(['out_member_no'=>$out_member_no])->update($up_data);
            if (!$up_res || empty($up_res)) {
                Db::rollback();
                $this->error('会员开户同步失败！');
            }

            $res = $this->lal_member_model->where(['lal_id'=>$lal_member_info['id']])->update(['card'=>$card_no,'member_no'=>$event['member_no'],'status'=>'1']);
            if (!$res || empty($res)) {
                Db::rollback();
                $this->error('会员开户同步失败！');
            }
            
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            write_log_record("会员开户结果同步失败,失败原因：".json_encode($e));
            $this->error($e->getMessage());
        }
        $this->success('会员开户同步成功！');
    }

    /**
     * 消费支付结果通知,拉卡拉官方接口回调，主要处理订单状态，以及第一次分账
     * 
     * */
    public function syncorder(){
        $params = $this->request->param();
        write_log_record("[".date("Y-m-d H:i:s")."]消费支付结果通知,参数：".json_encode($params));
        $event = $this->request->param('event','');
        if (!$event || empty($event)) {
            write_log_record("订单同步失败1");
            $this->error('订单同步失败！');
        }
        $event = json_decode($event,true);

        // $order_no = isset($event['out_order_no'])?$event['out_order_no']:'';//平台订单号
        $order_name = isset($event['order_name'])?$event['order_name']:'';//平台订单号
        $pay_seq_no = isset($event['pay_seq_no'])?$event['pay_seq_no']:'';//支付流水号（钱账通）

        if (!$order_name || empty($order_name) || !$pay_seq_no || empty($pay_seq_no)) {
            $this->error('缺少参数！');
        }

        // 创建数据
        Db::startTrans();
        try{
            $order_no = substr($order_name,3);
            $order_info = $this->order_model->where(['order_no'=>$order_no,'state'=>1])->find();
            if (!$order_info || empty($order_info)) {
                Db::rollback();
                write_log_record("订单同步失败2,order_no:".$order_no);
                $this->error('订单同步失败！');
            }

            //同步订单状态
            $order_state = $order_info['data_type'] == 'merchant'?2:6;
            $res = $this->order_model->where(['id'=>$order_info['id']])->update(['state'=>$order_state,'paymenttime'=>time(),'updatetime'=>time(),'dealtime'=>time()]);
            if (!$res || empty($res)) {
                Db::rollback();
                write_log_record("订单同步失败3");
                $this->error('订单状态修改失败！');
            }

            $lal_member_info = $this->lal_member_model->where(['shop_id'=>1])->find();
            if (!$lal_member_info || empty($lal_member_info)) {
                Db::rollback();
                write_log_record("订单同步失败4");
                $this->error('订单同步失败！');
            }

            //订单支付数据
            $condi = [];
            $condi['order_id'] = $order_info['id'];
            $condi['pay_way_id'] = ['in',[10,12]];
            $condi['status'] = 'normal';
            $pay_data = $this->pay_out_trade_model->where($condi)->find();
            if (!$pay_data || empty($pay_data)) {
                Db::rollback();
                write_log_record("支付数据不存在");
                $this->error('订单同步失败！');
            }

            $actual_price = sprintf("%.2f",$pay_data['price']);//订单实际支付金额
            $abalance = $lal_member_info['abalance']?sprintf("%.2f",$lal_member_info['abalance']):0;//结余账户
            $bbalance = $lal_member_info['bbalance']?sprintf("%.2f",$lal_member_info['bbalance']):0;//佣金账户
            //手续费为 5%
            $charge_fee = sprintf("%.2f",$actual_price * 0.005);
            //分账总金额
            // $left_total_fee = sprintf("%.2f",$actual_price * (1 - 0.005));
            //增加的结余金额
            $balance = sprintf("%.2f",sprintf("%.2f",$actual_price * 0.01) - $charge_fee);
            //增加的佣金
            $commission = sprintf("%.2f",$actual_price * 0.99);

            $abalance += $balance;
            $bbalance += $commission;
            
            $up_data = ['abalance'=>$abalance,'bbalance'=>$bbalance,'updatetime'=>time()];

            $res = $this->lal_member_model->where(['id'=>$lal_member_info['id']])->update($up_data);
            if (!$res || empty($res)) {
                Db::rollback();
                write_log_record("订单同步失败5");
                $this->error('订单同步失败！');
            }

            $inset_data = [];
            $inset_data['code'] = $pay_seq_no;
            $inset_data['tratime'] = time();
            $inset_data['order_id'] = $order_info['id'];
            $inset_data['shop_id'] = $order_info['shop_id'];
            $inset_data['orderno'] = $order_info['order_no'];
            $inset_data['amount'] = $actual_price;
            $inset_data['abalance'] = $balance;
            $inset_data['bbalance'] = $commission;
            $inset_data['charge'] = $charge_fee;
            $inset_data['createtime'] = time();

            $res = $this->lal_member_entry_model->insert($inset_data);
            if (!$res || empty($res)) {
                Db::rollback();
                write_log_record("订单同步失败6");
                $this->error('订单同步失败！');
            }

            //更新支付数据
            $update_data = [];
            $update_data['out_trade_no'] = $event['order_no'];
            // $update_data['pay_way_id'] = 10;
            $res = $this->pay_out_trade_model->where(['id'=>$pay_data['id']])->update($update_data);
            if (!$res || empty($res)) {
                Db::rollback();
                write_log_record("订单同步失败7");
                $this->error('订单同步失败！');
            }

            //更新支付日志表
            $condi = [];
            $condi['order_id'] = $order_info['id'];
            $condi['pay_way_id'] = $pay_data['pay_way_id'];
            $condi['status'] = 'normal';


            $update_data = [];
            $update_data['pay_type'] = $event['third_party_payment'] == 'ALIPAY'?2:1;
            $update_data['pay_state'] = 1;
            $res = $this->wanlshop_pay_model->where($condi)->update($update_data);
            if (!$res || empty($res)) {
                Db::rollback();
                write_log_record("订单同步失败8");
                $this->error('订单同步失败！');
            }

            //同步订单卡项
            //获取订单相关的卡项
            $condi = [];
            $condi['order_id'] = $order_info['id'];
            // $condi['status'] = 'hidden';
            $order_items = $this->order_item_model->where($condi)->select();

            if (count($order_items)>0) {
                foreach ($order_items as $key => $value) {
                    if ($order_info['isrecharge'] == 0 && $value['status'] == 'hidden') {
                        $res = $this->order_item_model->where(['id'=>$value['id']])->update(['status'=>'normal','updatetime'=>time()]);
                        if (!$res || empty($res)) {
                            Db::rollback();
                            write_log_record("同步订单卡项失败1");
                            exception('订单同步失败！');
                        }

                        $order_item_info_ids = $this->order_item_info_model->where(['order_item_id'=>$value['id'],'status'=>'hidden'])->column('id');
                        if (count($order_item_info_ids)>0) {
                            $res = $this->order_item_info_model->where(['id'=>['in',$order_item_info_ids]])->update(['status'=>'normal','updatetime'=>time()]);
                            if (!$res || empty($res)) {
                                Db::rollback();
                                write_log_record("同步订单卡项失败2");
                                exception('订单同步失败！');
                            }
                        }

                    }
                }
            }

            //处理充值数据
            if ($order_info['isrecharge'] == 1){
                //查询数据
                $recharges = $this->order_item_recharge_model->where('order_id',$order_info['id'])->select();

                if (count($recharges)>0) {
                    foreach ($recharges as $k => $v) {
                        $condi = [];
                        $condi['id'] = $v['order_item_id'];
                        $order_items = $this->order_item_model->where($condi)->find();

                        $res = $this->order_item_recharge_model->where('id',$v['id'])->update(['state'=>'2','updatetime'=>time()]);
                        if(!$res){
                            write_log_record("充值卡续费数据处理失败1");
                            Db::rollback();
                            exception('订单同步失败！');
                        }

                        $update_data = [];
                        $update_data['gift'] = sprintf("%.2f", $order_items['gift'] + $v['gift']);
                        $update_data['spent'] = sprintf("%.2f", $order_items['spent'] + $v['actual_price']);
                        $update_data['total'] = sprintf("%.2f", $order_items['total'] + $v['gift'] + $v['actual_price']);
                        $update_data['updatetime'] = time();

                        $res = $this->order_item_model->where('id',$v['order_item_id'])->update($update_data);
                        if(!$res){
                            write_log_record("充值卡续费数据处理失败2");
                            Db::rollback();
                            exception('订单同步失败！');
                        }
                    }
                }
            }

            $push=[];
            $msg = Db::name('order_push_msg')->where(['state'=>0,'order_id'=>$order_info['id']])->find();
            if($msg){
                $push =json_decode($msg['content'],true);
                $temp =\config('msg_template');

                $url = cdnurl('/api/Weixin/sentMsg',true);//拉卡拉退款接口
                foreach ($push as $key=>$value){
                    if($key=='card_success'){
                        foreach ($value as $val){
                            $content=$temp[$key]['content'];
                            $content['thing7']['value'] =$val['title'];
                            $content['thing10']['value'] =$val['card_name'];
                            $content['amount4']['value'] =sprintf('%.2f',$val['price']);
                            $content['time1']['value'] =$val['time'];
                            $content['thing6']['value'] =$val['shop'];
                            $param=[];
                            $param['template_id']=$temp[$key]['template_id'];
                            $param['content']=json_encode($content);
                            $param['open_id']=$val['open_id'];
                            $result = curlPost($url,$param);

                        }

                    }elseif ($key=='recharge'){
                        foreach ($value as $val){
                            $content=$temp[$key]['content'];
                            $content['thing10']['value'] =$val['shop'];
                            $content['thing11']['value'] =$val['card_name'];
                            $content['amount2']['value'] =sprintf('%.2f',$val['recharge']);
                            $content['time4']['value'] =$val['time'];
                            $content['amount3']['value'] =sprintf('%.2f',$val['balance']);
                            $param=[];
                            $param['template_id']=$temp[$key]['template_id'];
                            $param['content']=json_encode($content);
                            $param['open_id']=$val['open_id'];
                            $result = curlPost($url, $param);

                        }

                    }elseif ($key=='shop_card_times_success'){
                        foreach ($value as $val){
                            $content=$temp[$key]['content'];
                            $content['amount4']['value'] =sprintf('%.2f',$val['order_price']);
                            $content['time11']['value'] =$val['time'];

                            $param=[];
                            $param['template_id']=$temp[$key]['template_id'];
                            $param['content']=json_encode($content);
                            $param['open_id']=$val['open_id'];
                            $result = curlPost($url, $param);

                        }
                    }elseif ($key==='times_card_pay_success'){
                        //'shop_name'=>$shopPo[$this->shop_id]??"",
                        //                                'pay_way'=>'会员权益',
                        //                                'use_times'=>$val + $push['times_card_pay_success'][$key]['use_times'],
                        foreach ($value as $val){
                            $content=$temp[$key]['content'];
                            $content['thing12']['value'] =$val['shop_name'];
                            $content['thing9']['value'] ="本次耗卡{$val['use_times']}次";
                            $content['phrase8']['value'] =$val['pay_way'];

                            $param=[];
                            $param['template_id']=$temp[$key]['template_id'];
                            $param['content']=json_encode($content);
                            $param['open_id']=$val['open_id'];
                            $result = curlPost($url, $param);

                        }
                    }elseif ($key==='card_pay_success'){
                        //'consume_service'=>join(',',$consume_service),
                        //                    'order_price'=>$orderCount['totalfee'],
                        //                    'time'=>date('Y-m-d H:i:s',time()),
                        //                    'pay_way'=>'会员余额',
                        //                    'balance'=>$update_data['spent'] + $update_data['gift'],
                        foreach ($value as $val){
                            $content=$temp[$key]['content'];
                            $content['thing13']['value'] =$val['consume_service'];
                            $content['amount4']['value'] =sprintf('%.2f',$val['order_price']);
                            $content['time5']['value'] =$val['time'];
                            $content['phrase8']['value'] =$val['pay_way'];
                            $content['amount14']['value'] =sprintf('%.2f',$val['balance']);

                            $param=[];
                            $param['template_id']=$temp[$key]['template_id'];
                            $param['content']=json_encode($content);
                            $param['open_id']=$val['open_id'];
                            $result = curlPost($url, $param);

                        }
                    }
                }
                Db::name('order_push_msg')->where(['id'=>$msg['id']])->update(['state'=>1]);
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            write_log_record("订单同步失败9");
            write_log_record("同步失败,失败原因：".json_encode($e));
            $this->error($e->getMessage());
        }
        return $this->success('订单同步成功！');
    }

    public function refund()
    {
        $params = $this->request->param();
        write_log_record("[".date("Y-m-d H:i:s")."]退款接口,参数：".json_encode($params));
        $order_no = isset($params['order_no'])?$params['order_no']:'';
        $order_info = $this->order_model->where(['order_no'=>$order_no,'state'=>['<>','1']])->find();
        if (!$order_info || empty($order_info)) {
            $this->error('订单不存在');
        }

        //拉卡拉一次分账信息
        $lal_member_entry_info = $this->lal_member_entry_model->where(['order_id'=>$order_info['id']])->find();
        if (!$lal_member_entry_info || empty($lal_member_entry_info)) {
            $this->error('分账信息不存在');
        }

        //第三方支付信息
        $order_trade_info = $this->pay_out_trade_model->where(['order_id'=>$order_info['id']])->find();
        if (!$order_trade_info || empty($order_trade_info)) {
            $this->error('支付信息不存在');
        }

        $req_params = [];
        // 原订单（需要退款的订单编号）
        $req_params['order_no'] = $order_trade_info['out_trade_no'];

        // 应用平台请求号（对应消费下单时返回的字段pay_order_no）
        $req_params['out_request_no'] = create_order_sn($order_info['id']);

        // 支付流水号
        $req_params['pay_seq_no'] = $lal_member_entry_info['code'];

        // 退款金额 
        $req_params['refund_amount'] = (string)sprintf("%.0f",$order_trade_info['price'] * 100);

        // 退款规则
        $amount = sprintf("%.0f",$order_trade_info['price'] * 100);
        $commission = sprintf("%.0f",$amount * 0.99);//佣金
        $left_commission = sprintf("%.0f",$amount - $commission);

        if ($commission == $amount) {
            $req_params['refund_rule']= [
                ['member_no' => Config::get('lal_config.member_no'), 'amount' => (string)$amount],
            ];
        }else{
            $req_params['refund_rule']= [
                ['member_no' => Config::get('lal_config.member_no'), 'amount' => (string)$commission,'special_account_no' => 'S005'],
                ['member_no' => Config::get('lal_config.member_no'), 'amount' => (string)$left_commission],
            ];
        }

        $req_url = cdnurl('/api/Pay/refund',true);//拉卡拉退款接口
        write_log_record("[".date("Y-m-d H:i:s")."]退款接口参数：".json_encode($req_params));
        $result = send_request($req_url, json_encode($req_params),'POST');
        write_log_record("[".date("Y-m-d H:i:s")."]退款结果：".json_encode($result));
        if ($result && !empty($result)) {
            if ($result['data']['status'] == 'OK') {
                $res = $this->order_model->where(['id'=>$order_info['id']])->update(['state'=>7,'updatetime'=>time()]);
                $this->success('订单退款成功！',$result['data']); 
            }else{
                $this->error('退款失败，请稍后重试',$result['data']);
            }
        }
        $this->error('退款失败，请稍后重试');
    }
    public function refundV2()
    {
        $params = $this->request->param();
//        $params['order_no']='174462758158166000000003093';
//        $params['refund_price']=0.02;

        write_log_record("[".date("Y-m-d H:i:s")."]退款接口参数请求参数---：".json_encode($params));
        $order_no = isset($params['order_no'])?$params['order_no']:'';
        $refundPrice = $params['refund_price'] ?? 0;
        $order_info = $this->order_model->where(['order_no'=>$order_no,'state'=>['<>','1']])->find();
        $refundParam=[];
        $refundParam['param_data']=json_encode($params);
        $refundParam['order_id'] =$order_info['id'];
        $refundParam['create_time'] =time();
        Db::name('order_refund_log')->insert($refundParam);
        if (!$order_info || empty($order_info)) {
            $this->error('订单不存在');
        }

        //拉卡拉一次分账信息
        $lal_member_entry_info = $this->lal_member_entry_model->where(['order_id'=>$order_info['id']])->find();
        if (!$lal_member_entry_info || empty($lal_member_entry_info)) {
            $this->error('分账信息不存在');
        }

        //第三方支付信息
        $order_trade_info = $this->pay_out_trade_model->where(['order_id'=>$order_info['id']])->find();
        if (!$order_trade_info || empty($order_trade_info)) {
            $this->error('支付信息不存在');
        }

        $req_params = [];
        // 原订单（需要退款的订单编号）
        $req_params['order_no'] = $order_trade_info['out_trade_no'];

        // 应用平台请求号（对应消费下单时返回的字段pay_order_no）
        $req_params['out_request_no'] = create_order_sn($order_info['id']);

        // 支付流水号
        $req_params['pay_seq_no'] = $lal_member_entry_info['code'];

        // 退款金额
        $order_trade_info['price']= $refundPrice;
        $req_params['refund_amount'] = (string)sprintf("%.0f",$order_trade_info['price'] * 100);

        // 退款规则

        $amount = sprintf("%.0f",$order_trade_info['price'] * 100);
        $commission = sprintf("%.0f",$amount * 0.99);//佣金
        $left_commission = sprintf("%.0f",$amount - $commission);

        if ($commission == $amount) {
            $req_params['refund_rule']= [
                ['member_no' => Config::get('lal_config.member_no'), 'amount' => (string)$amount],
            ];
        }else{
            $req_params['refund_rule']= [
                ['member_no' => Config::get('lal_config.member_no'), 'amount' => (string)$commission,'special_account_no' => 'S005'],
                ['member_no' => Config::get('lal_config.member_no'), 'amount' => (string)$left_commission],
            ];
        }

        $req_url = cdnurl('/api/Pay/refund',true);//拉卡拉退款接口
        write_log_record("[".date("Y-m-d H:i:s")."]退款接口参数：".json_encode($req_params));
        $result = send_request($req_url, json_encode($req_params),'POST');
        write_log_record("[".date("Y-m-d H:i:s")."]退款结果：".json_encode($result));
        $refundParam=[];
        $refundParam['param_data']=json_encode($result);
        $refundParam['order_id'] =$order_info['id'];
        $refundParam['create_time'] =time();
        Db::name('order_refund_log')->insert($refundParam);
        if ($result && !empty($result)) {
            if ($result['data']['status'] == 'OK') {
                $res = $this->order_model->where(['id'=>$order_info['id']])->update(['state'=>7,'updatetime'=>time()]);
                $this->success('订单退款成功！',$result['data']);
            }else{
                $this->error('退款失败，请稍后重试',$result['data']);
            }
        }
        $this->error('退款失败，请稍后重试');
    }
    //查询账户余额
    public function findBalance()
    {
        $req_params = ['member_no' => Config::get('lal_config.member_no'), 'account_type' => '1000','special_account_no'=>'S005'];
        $req_url = cdnurl('/api/Pay/findBalance',true);//拉卡拉退款接口
        write_log_record("[".date("Y-m-d H:i:s")."]查询账户余额接口参数：".json_encode($req_params));
        $result = send_request($req_url, json_encode($req_params),'POST');
        write_log_record("[".date("Y-m-d H:i:s")."]查询账户余额结果：".json_encode($result));
        if ($result && !empty($result)) {
            if ($result['data']['status'] == 'OK') {
               $this->success('查询成功！',$result['data']);
            }else{
                $this->error('查询失败！',$result['data']);
            }
        }
        $this->error('查询失败，请稍后重试');
    }

    //托管账户查询余额
    public function findTrustBalance()
    {
        $req_params = ['member_no' => Config::get('lal_config.member_no'), 'trust_type' => 'pingan'];
        $req_url = cdnurl('/api/Pay/findTrustBalance',true);//拉卡拉退款接口
        write_log_record("[".date("Y-m-d H:i:s")."]查询托管账户余额接口参数：".json_encode($req_params));
        $result = send_request($req_url, json_encode($req_params),'POST');
        write_log_record("[".date("Y-m-d H:i:s")."]查询托管账户余额结果：".json_encode($result));
        if ($result && !empty($result)) {
            if ($result['data']['status'] == 'OK') {
               $this->success('查询成功！',$result['data']);
            }else{
                $this->error('查询失败！',$result['data']);
            }
        }
        $this->error('查询失败，请稍后重试');
    }

    //商户佣金专用账户分账
    public function split()
    {
        $req_params = $this->request->param();
        $req_url = cdnurl('/api/Pay/split',true);//分账接口
        write_log_record("[".date("Y-m-d H:i:s")."]拉卡拉转账接口参数：".json_encode($req_params));
        $result = send_request($req_url, json_encode($req_params),'POST');
        write_log_record("[".date("Y-m-d H:i:s")."]拉卡拉转账结果：".json_encode($result));
        if ($result && !empty($result)) {
            if ($result['data']['status'] == 'OK') {
               $this->success('分账成功！',$result['data']);
            }else{
                $this->error('分账失败！',$result['data']);
            }
        }
        $this->error('分账失败，请稍后重试');
    }

    //会员绑卡相关页面
    public function getBankCardPage()
    {
        $req_params = $this->request->param();
        $req_url = cdnurl('/api/Pay/bankCard',true);//会员绑卡相关页面接口
        write_log_record("[".date("Y-m-d H:i:s")."]会员绑卡相关页面接口参数：".json_encode($req_params));
        $result = send_request($req_url, $req_params,'GET');
        write_log_record("[".date("Y-m-d H:i:s")."]会员绑卡相关页面结果：".json_encode($result));
        if ($result && !empty($result)) {
            if ($result['data']['status'] == 'OK') {
               $this->success('获取成功！',$result['data']['result']);
            }else{
                $this->error('获取失败！失败原因：'.$result['data']['message']);
            }
        }
        $this->error('操作失败，请稍后重试');
    }

    /**
     * 银行卡页面相关操作结果通知
     * 1、operate_type  1：绑卡     2：解绑    3：设置结算卡
     * 2、bank_card_no   银行卡号
     * 3、is_settle_card  是否结算卡 true/false
     * */
    
    public function syncBankCard()
    {
        $params = $this->request->param();
        write_log_record("[".date("Y-m-d H:i:s")."]银行卡页面相关操作结果通知,参数：".json_encode($params));

        $event_type = $this->request->param('event_type','');
       
        $event = $this->request->param('event','');

        if (!$event_type || $event_type != 'member.bank.card' || !$event || empty($event)) {
            $this->error('参数错误');
        }
        
        $event = json_decode($event,true);

        $member_no = isset($event['member_no'])?$event['member_no']:'';

        $operate_type = isset($event['operate_type'])?$event['operate_type']:'';

        $bank_card_no = isset($event['bank_card_no'])?$event['bank_card_no']:'';

        $is_settle_card = isset($event['is_settle_card']) && $event['is_settle_card'] == true?1:2;

        if (!$operate_type || empty($operate_type) || !$member_no || empty($member_no) || !$bank_card_no || empty($bank_card_no)) {
            $this->error('缺少参数！');
        }

        $where = [];
        $where['member_no'] = $member_no;
        $where['card_no'] = $bank_card_no;

        $lal_member_info = $this->lal_member_info_model->where($where)->find();
        Db::startTrans();
        try{
            if ($operate_type == 1) {//绑卡,新增银行卡记录
                if(!empty($lal_member_info)){
                    Db::rollback();
                    $this->error('当前银行卡已存在！');
                }
                $inset_data = [];
                $inset_data['member_no'] = $event['member_no'];
                $inset_data['mobile'] = $event['mobile'];
                $inset_data['card_no'] = $bank_card_no;
                $res = $this->lal_member_info_model->insert($inset_data);
                if(empty($res)){
                    Db::rollback();
                    $this->error('银行卡绑定失败！');
                }
            }else if ($operate_type == 2) {//解绑,解除银行卡绑定
                if(empty($lal_member_info)){
                    Db::rollback();
                    $this->error('当前银行卡不存在！');
                }
                $res = $this->lal_member_info_model->delete($where);
                if(empty($res)){
                    Db::rollback();
                    $this->error('银行卡绑定失败！');
                }
            }else if ($operate_type == 3) {//设置结算卡，设置当前
                if(empty($lal_member_info)){
                    Db::rollback();
                    $this->error('当前银行卡不存在！');
                }
                $up_data = [];
                $up_data['is_settle_card'] = $is_settle_card;
                $res = $this->lal_member_info_model->where($where)->update($up_data);
                if(empty($res)){
                    Db::rollback();
                    $this->error('银行卡设置失败！');
                }
            }
            
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            write_log_record("银行卡操作结果同步失败,失败原因：".json_encode($e));
            $this->error($e->getMessage());
        }
        $this->success('银行卡操作结果同步成功！');
    }
}
